package cn.gzjp.modules.rice.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.gzjp.common.config.Global;
import cn.gzjp.common.mapper.JsonMapper;
import cn.gzjp.common.utils.*;
import cn.gzjp.common.web.AjaxResult;
import cn.hutool.http.HtmlUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.rice.entity.RiceProduct;
import cn.gzjp.modules.rice.service.RiceProductService;

/**
 * 产品管理Controller
 * @author zengcp
 * @version 2018-11-17
 */
@Controller
@RequestMapping(value = "${adminPath}/rice/riceProduct")
public class RiceProductController extends BaseController {

	@Autowired
	private RiceProductService riceProductService;
	
	
	/**
	 * 产品列表页面
	 */
	@RequiresPermissions("rice:riceProduct:list")
	@RequestMapping(value = {"list", ""})
	public String list(RiceProduct riceProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RiceProduct> page = riceProductService.findPage(new Page<RiceProduct>(request, response), riceProduct); 
		model.addAttribute("page", page);
		return "modules/rice/riceProductList";
	}

	/**
	 * 查看，增加，编辑产品表单页面
	 */
	@RequiresPermissions(value={"rice:riceProduct:view","rice:riceProduct:add","rice:riceProduct:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(RiceProduct riceProduct, Model model) {
		model.addAttribute("riceProduct", riceProduct);
		return "modules/rice/riceProductForm";
	}

	/**
	 * 保存产品
	 */
	@RequiresPermissions(value={"rice:riceProduct:add","rice:riceProduct:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(RiceProduct riceProduct, Model model, RedirectAttributes redirectAttributes) throws Exception{
		riceProduct.setContent(Encodes.unescapeHtml(riceProduct.getContent()));
		if(StringUtils.isNoneBlank(riceProduct.getContent())&&!riceProduct.getContent().startsWith("<p")){
			String content = HtmlUtil.cleanHtmlTag(riceProduct.getContent());
			riceProduct.setContent(content);
		}
		if (!beanValidator(model, riceProduct)){
			return form(riceProduct, model);
		}
		if(!riceProduct.getIsNewRecord()){//编辑表单保存
			RiceProduct t = riceProductService.get(riceProduct.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(riceProduct, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			riceProductService.save(t);//保存
		}else{//新增表单保存
			riceProductService.save(riceProduct);//保存
		}
		addMessage(redirectAttributes, "保存产品成功");
		return redirect("/rice/riceProduct/?repage");
	}
	
	/**
	 * 删除产品
	 */
	@RequiresPermissions("rice:riceProduct:del")
	@RequestMapping(value = "delete")
	public String delete(RiceProduct riceProduct, RedirectAttributes redirectAttributes) {
		riceProductService.delete(riceProduct);
		addMessage(redirectAttributes, "删除产品成功");
		return redirect("/rice/riceProduct/?repage");
	}
	
	/**
	 * 批量删除产品
	 */
	@RequiresPermissions("rice:riceProduct:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			riceProductService.delete(riceProductService.get(id));
		}
		addMessage(redirectAttributes, "删除产品成功");
		return redirect("/rice/riceProduct/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("rice:riceProduct:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(RiceProduct riceProduct, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "产品"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<RiceProduct> page = riceProductService.findPage(new Page<RiceProduct>(request, response, -1), riceProduct);
    		new ExportExcel("产品", RiceProduct.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出产品记录失败！失败信息："+e.getMessage());
		}
		return redirect("/rice/riceProduct/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("rice:riceProduct:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RiceProduct> list = ei.getDataList(RiceProduct.class);
			for (RiceProduct riceProduct : list){
				try{
					riceProductService.save(riceProduct);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条产品记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条产品记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入产品失败！失败信息："+e.getMessage());
		}
		return redirect("/rice/riceProduct/?repage");
    }
	
	/**
	 * 下载导入产品数据模板
	 */
	@RequiresPermissions("rice:riceProduct:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "产品数据导入模板.xlsx";
    		List<RiceProduct> list = Lists.newArrayList(); 
    		new ExportExcel("产品数据", RiceProduct.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/rice/riceProduct/?repage");
    }
	@ModelAttribute
	public RiceProduct get(@RequestParam(required=false) String id) {
		RiceProduct entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = riceProductService.get(id);
		}
		if (entity == null){
			entity = new RiceProduct();
		}
		return entity;
	}


	/**
	 * 图片上传
	 * @param request
	 * @param file
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = "imageUpload")
	@ResponseBody
	public String imageUpload( HttpServletRequest request,MultipartFile file) throws IllegalStateException, IOException {
		AjaxResult result = new AjaxResult(false,"");
		// 判断文件是否为空
		if (!file.isEmpty()) {
			// 文件保存路径
			String realPath = Global.USERFILES_BASE_URL+"/upload_images/" ;
			// 转存文件
			FileUtils.createDirectory(Global.getUserfilesBaseDir()+realPath);
			String extension = FilenameUtils.getExtension(file
					.getOriginalFilename());
			String mmddss = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			String fileName = mmddss+"."+extension;

			file.transferTo(new File( Global.getUserfilesBaseDir() +realPath +  fileName));
			String img = request.getContextPath()+realPath + fileName;
			result.setSuccess(true);
			result.setMsg(img);
		}
		return JsonMapper.getInstance().toJson(result);
	}

}